const Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8545'));
const private_key = '0x47a2b5b4346ad3676722cb130b1818f4f57094ed555dc61498d8d10b0daa2e9e';
// root
const eth_address = '0xb85cA0627Fc1A08eBc41378d2328b9EA70512Db0';
const fs = require('fs');
const contractJson = JSON.parse(fs.readFileSync('/home/fredyvia/digital-identity-management/build/contracts/DigitalIdentityManagement.json', 'utf8'));
const contractAbi = contractJson.abi;
const contractAddr = contractJson.networks['5777'].address;
console.log(contractAddr);
var contract = new web3.eth.Contract(contractAbi, contractAddr, { from: eth_address });

function sha256(data) {
  return crypto.createHash('sha256').update(data).digest()
}

const { MerkleTree } = require('merkletreejs')
const crypto = require('crypto')
const express = require('express');

const app = express();
const port = 3001;

app.use(express.static('../frontend/build'));
app.use(express.json())

app.post('/verify', async function (req, resp) {
  console.log(req.body);

  var sha = req.body.salt_seed;
  var salts = [];
  for (var i = 0; i <= req.body.count; i++) {
    sha = sha256(sha).toString("hex");
    salts.push(sha);
  }
  res_obj = req.body.indices.map(obj => {
    return { index: obj.index, leave: sha256(obj.value 
      + req.body.sep + salts[obj.index]) }
  })
  console.log(res_obj);
  var result = {}
  result.merkleCheck = new MerkleTree([], sha256)
    .verifyMultiProof(req.body.merkle_root
    , res_obj.map(obj => obj.index), res_obj.
    map(obj => obj.leave), req.body.count, req.body.proof);
  console.log(result);
  if (result.merkleCheck == false) {
    resp.send(result);
    return;
  }
  issuerAddress = web3.eth.accounts.recover(req.body.merkle_root, req.body.merkle_root_signature);
  result.link = []
  while (true) {
    var res = await contract.methods.getDidByDidSymbol(req.body.did).call()
    if (res.issueDidSymbol == req.body.did)
      break;
    req.body.did = res.issueDidSymbol;
    result.link.push({
      did: res.didMethodName + ':' + res.didId,
      issueDatetime: res.issueDatetime,
      validDatetime: res.validDatetime,
      userAddr: res.userAddr,
      issueDidSymbol: res.issueDidSymbol
    });
  }
  result.link = result.link.reverse();
  console.log(result.link);
  resp.send(result);
})
app.listen(port, () => {
  console.log(`ca backend listening on port ${port}`);
})
